<template>
  <div>
    <!-- 角色 -->
    <dtDialog
      title="授权角色"
      :visible.sync="roleDialogFormVisible"
      :is-loading="loading"
      @closeDialog="closeRoleDialog()"
      @comfirmBtn="submitRole()"
    >
      <el-form
        ref="roleDataForm"
        slot="content"
        :rules="roleRules"
        :model="roleTemp"
        label-position="right"
        label-width="82px"
        style="width: 100%"
      >
        <el-form-item label="选择角色" prop="grantRoleIdList">
          <el-select v-model="roleTemp.grantRoleIdList" clearable multiple placeholder="请选择" style="width: 100%">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
    </dtDialog>
  </div>
</template>

<script>
import sysUserApi from '@/framework/api/userCenter/sysUser'
import roleApi from '@/framework/api/permissionCenter/roleManage'
export default {
  data() {
    return {
      loading: false,
      roleDialogFormVisible: false,
      roleTemp: {
        grantRoleIdList: []
      },
      selectedOrg: {},
      roleRules: {
        grantRoleIdList: [{
          required: true,
          message: '请选择角色',
          trigger: 'change'
        }]
      },
      roleList: []
    }
  },
  methods: {
    initRoleList() {
      roleApi.dropDown().then(res => {
        this.roleList = res.data
      })
    },
    setRole(row) {
      this.initRoleList()
      sysUserApi.detail(row.userId).then((res) => {
        const arr = res.data.grantRoleInfosList.map(el => {
          return el.roleId
        })
        this.roleTemp.grantRoleIdList = arr
        this.roleTemp.userId = res.data.userId
        this.roleDialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['roleDataForm'].clearValidate()
        })
      })
    },
    submitRole() {
      this.$refs['roleDataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.roleTemp.select = this.roleTemp.grantRoleIdList.toString()
          try {
            roleApi.grantRole(this.roleTemp).then(res => {
              this.$parent.getList()
              this.roleDialogFormVisible = false
              this.$dtMessage({
                message: '授权成功',
                type: 'success'
              })
            })
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    closeRoleDialog() {
      this.roleTemp = {
        grantRoleIdList: []
      }
    }
  }
}
</script>
